package cn.likole.oj.module.admin;


import cn.likole.oj.bean.Problem;
import cn.likole.oj.utils.Toolkit;
import org.nutz.dao.*;
import org.nutz.dao.pager.Pager;
import org.nutz.img.Images;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.plugins.apidoc.annotation.Api;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;

@At("/admin")
@IocBean
@Api(name = "后台管理")
@Filters(@By(type = CheckSession.class,args = {"problemSetter","/"}))
public class ProadminModule {

    @Inject
    private Dao dao;


    private void RemoveXss(Problem problem){
        if(problem==null)return ;
        if(problem.getTitle()!=null)
            Strings.escapeHtml(problem.getTitle());
        if(problem.getDescription()!=null)
            Strings.escapeHtml(problem.getDescription());
        if(problem.getInput()!=null)
            Strings.escapeHtml(problem.getInput());
        if(problem.getOutput()!=null)
            Strings.escapeHtml(problem.getOutput());
        if(problem.getSampleInput()!=null)
            Strings.escapeHtml(problem.getSampleInput());
        if(problem.getSampleOutput()!=null)
            Strings.escapeHtml(problem.getSampleOutput());
        if(problem.getSpj()!=null)
            Strings.escapeHtml(problem.getSpj());
        if(problem.getHint()!=null)
            Strings.escapeHtml(problem.getHint());
        if(problem.getSource()!=null)
            Strings.escapeHtml(problem.getSource());
    }

    @At
    @Api(name = "问题列表")
    public Object getProList(HttpSession session, @Param("src/main")Pager pager){
        pager.setRecordCount(dao.count(Problem.class));
        return new QueryResult(dao.query(Problem.class,null,pager),pager);
    }

    @At
    @Api(name = "设置问题状态")
    public Object setProStatus(HttpSession session,@Param("pid")int pid){
        NutMap re=new NutMap();
        Problem problem=dao.fetch(Problem.class,pid);
        if(problem==null)
            return re.setv("ok",false).setv("msg","问题不存在");
        if(problem.isValid())
            problem.setValid(false);
        else
            problem.setValid(true);
        int rows=dao.update(problem);
        if(rows==0)
            return re.setv("ok",false).setv("msg","更新失败");
        return re.setv("ok",false);
    }

    @At("editProblem")
    @Api(name = "编辑问题")
    @GET
    public Object getProblem(HttpSession session,@Param("pid")int pid){
        NutMap re=new NutMap();
        Problem problem=dao.fetch(Problem.class,pid);
        if(problem==null)
            return re.setv("ok",false).setv("msg","问题不存在");
        return re.setv("ok",true).setv("problem",problem);
    }

    @At("editProblem")
    @Api(name = "编辑问题")
    @POST
    public Object editProblem(HttpSession session,@Param("src/main")Problem problem){
        NutMap re=new NutMap();
        RemoveXss(problem);
        int rows=dao.update(problem);
        if(rows==0)
            return re.setv("ok",false).setv("msg","更新失败");
        return re.setv("ok",true).setv("problem",problem);
    }


    @At
    public Object addProblem(HttpSession session,@Param(",,")Problem problem){
        NutMap re=new NutMap();
        RemoveXss(problem);
        problem=dao.insert(problem);
        if(problem==null)
            return re.setv("ok",false).setv("msg","更新失败");
        return re.setv("ok",true).setv("problem",problem);
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"${app.root}/WEB-INF/tmp_propic/problem_pic", "8192", "utf-8", "20000", "1024000"})
    @POST
    @At("/pic")
    public Object uploadPic(@Param("file") TempFile tf, HttpSession session, AdaptorErrorContext err,@Param("pid")int id) {
        NutMap re = new NutMap();
        if (err != null && err.getAdaptorErr() != null) {
            return re.setv("ok",false).setv("msg","上传文件大小不符合规定");
        } else if (tf == null) {
            return re.setv("ok",false).setv("msg","空文件");
        } else {
            try {
                BufferedImage image = Images.read(tf.getFile());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Images.writeJpeg(image, out, 0.9f);
                String src="${app.root}/WEB-INF/propic/"+ Toolkit.getUUID()+".png";
                ImageIO.write(image,"png",new File(src));
            } catch (DaoException e) {
                return re.setv("ok",false).setv("msg","系统错误");
            } catch (Throwable e) {
                return re.setv("ok",false).setv("msg","图片格式错误");
            }
        }
        return re.setv("ok", true).setv("src", "上传成功");
    }


}
